package com.wh.wisdomsite.xbox.st.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wh.wisdomsite.xbox.ba.dao.SysSequenceMapper;
import com.wh.wisdomsite.xbox.core.XboxException;
import com.wh.wisdomsite.xbox.st.dao.ContractMapper;
import com.wh.wisdomsite.xbox.st.entity.Contract;
import com.wh.wisdomsite.xbox.st.service.IContractService;
import com.wh.wisdomsite.xbox.utils.Const;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 合同信息serviceImpl
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.st.service.impl
 * @date 2018年12月24日 14:31
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Service("contractService")
@Transactional(rollbackFor = {Exception.class, RuntimeException.class})
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {

    private static final Log logger = LogFactory.getLog(ContractServiceImpl.class);

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private SysSequenceMapper sysSequenceMapper;

    /**
     * 合同单编号
     */
    private static final Map<String, String> numberMap;
    static
    {
        numberMap = new HashMap<String, String>();
        numberMap.put("1", "00000000000");
        numberMap.put("2", "0000000000");
        numberMap.put("3", "000000000");
        numberMap.put("4", "00000000");
        numberMap.put("5", "0000000");
        numberMap.put("6", "000000");
        numberMap.put("7", "00000");
        numberMap.put("8", "0000");
        numberMap.put("9", "000");
        numberMap.put("10", "00");
        numberMap.put("11", "0");
    }

    /**
     * 合同单号前缀
     */
    private final static String COCODEFRONT = "HTD";

    @Override
    public Map<String, Object> getMapById(Serializable id) {
        return contractMapper.getMapById(id);
    }

    @Override
    public Page<Map<String, Object>> getMapsPage(Page page, Wrapper<Contract> wrapper) {
        SqlHelper.fillWrapper(page,wrapper);
        page.setRecords(this.baseMapper.getMapsPage(page,wrapper));
        return page;
    }

    @Override
    public void saveContract(String userId, Contract contract) throws Exception{
        if (StringUtils.isNotEmpty(contract.getCoId())) {
            logger.info("修改合同-->>开始");
            contract.setUpdateDate(new Date());
            contract.setUpdateBy(userId);
            contractMapper.updateById(contract);
            logger.info("修改合同-->>结束");
        } else {
            logger.info("添加合同-->>开始");
            //获取合同单号当前序列
            Map<String,Object> parmaMap = new HashMap<>();
            parmaMap.put("seqName",Const.COCODE_SEQ);
            parmaMap.put("seqValue",null);
            sysSequenceMapper.getSeqNextVal(parmaMap);
            Object coSeq = parmaMap.get("seqValue");
            if(coSeq == null){
                throw new XboxException("合同序列为空，保存失败");
            }
            //序列长度
            String coSeqStr = String.valueOf(coSeq);
            String coSeqLen = String.valueOf(coSeqStr.length());
            //根据序列值得长度获取在前面需要补足的零
            String coConumber = numberMap.get(coSeqLen);
            //构造合同单号
            String coCode = COCODEFRONT + "_" + coConumber + coSeqStr;
            contract.setCoId(UUID.randomUUID().toString().replace("-", ""));
            contract.setCoCode(coCode);
            contract.setCreateBy(userId);
            contract.setCreateDate(new Date());
            contractMapper.insert(contract);
            logger.info("添加合同-->>结束");
        }
    }

    @Override
    public boolean coNumberIsExists(String coNumber, String oldCoNumber) {
        //判断是否有原始值，有原始值则为修改, 且原始值跟新值不相同，才进行查询，否则直接返回false
        if(StringUtils.isNotEmpty(oldCoNumber) && coNumber.equals(oldCoNumber)){
            return false;
        }
        //设置条件
        EntityWrapper<Contract> ew = new EntityWrapper<>();
        ew.setEntity(new Contract());
        ew.eq("coNumber", coNumber);
        return contractMapper.selectCount(ew) > 0;
    }
}
